// 元素
var container = document.getElementById('game');

// 游戏初始配置
var gameDefaultConfig = CONFIG || {};

/**
 * 整个游戏对象
 */
var GAME = {
  /**
   * 初始化函数,这个函数只执行一次
   * @param  {object} opts 
   * @return {[type]}      [description]
   */
  init: function (opts) {
    this.currentLevel = gameDefaultConfig.defaultLevel || 1;
    this.currentScore = 0;
    this.status = 'start';
    document.querySelector('.game-level').innerHTML = '当前level: ' + this.currentLevel;
    this.bindEvent();
  },
  bindEvent: function () {
    var self = this;
    var playBtn = document.querySelector('.js-play');
    var nextBtn = document.querySelector('.js-next');
    var replayBtn = document.querySelectorAll('.js-replay');
    // 开始游戏按钮绑定
    playBtn.onclick = function () {
      self.play();
    };
    // 继续游戏按钮绑定
    nextBtn.onclick = function () {
      self.play();
    };
    // 再玩一次按钮绑定
    replayBtn.forEach(function(item){
      item.addEventListener('click', function() {
        self.currentLevel = gameDefaultConfig.defaultLevel || 1;
        self.currentScore = 0;
        self.play();
      })
    });
  },
  /**
   * 更新游戏状态，分别有以下几种状态：
   * start  游戏前
   * playing 游戏中
   * failed 游戏失败
   * success 游戏成功
   * all-success 游戏通过
   * stop 游戏暂停（可选）
   */
  setStatus: function (status) {
    this.status = status;
    container.setAttribute("data-status", status);
  },
  play: function () {
    var self = this;
    this.setStatus('playing');
    var shootingGameOptions = Object.assign({}, {
      selector: '#canvas',
      level: self.currentLevel,
      defaultScores: self.currentScore,
      successCallback: function (options) {
        self.currentLevel = options.nextLevel;
        self.currentScore = options.scores;
        document.querySelector('.game-success .game-info-text').innerHTML = '下一个Level: ' + options.nextLevel;
        self.setStatus('success');
      },
      completedCallback: function(options) {
        self.setStatus('all-success');
      },
      failureCallback: function (options) {
        self.setStatus('failed');
        self.currentLevel = 1;
        self.currentScore = 0;
        document.querySelector('.game-failed .score').innerHTML = options.scores;
      }
    }, gameDefaultConfig);
    var shootingGameCanvas = new ShootingGameCanvas(shootingGameOptions);
    shootingGameCanvas.run();
  },
};


// 初始化
GAME.init();